import json, datetime
from typing import Tuple
from django.db.models.query import QuerySet
from django.core.paginator import Paginator
from django.db.models import Model

def to_json(models,*ignore):
    """
    QuerySet 转json
    models: QuerySet对象
    *ingrore: 过滤字段
    """
    class __encode(json.JSONEncoder):
        def default(self, o):
            try:
                if type(o) == datetime.datetime:
                    return o.strftime('%Y-%m-%d %H:%M:%S')
                _dict = o.__dict__.copy()
                for i in o.__dict__.keys():
                    if i.startswith("_") or i in ignore:
                        _dict.pop(i)
                return _dict
            except Exception as  e:
                pass
    if type(models) == QuerySet:
        return json.dumps(list(models), cls=__encode)
    else:
        return json.dumps(models, cls=__encode)

def to_page(models, page_index, page_size=10):
    """
        分页查询
        models 查询的model
        page_index 页码
        page_size 页行数
    """
    try:
        if type(models) != QuerySet:
            models = models.all()
        paginator = Paginator(models, page_size)
        return paginator.page(page_index).object_list
    except Exception as e:
        return []

def pages(model: Model, size: int, index: int, count: bool =False)->Tuple[Model, int, int]: 
    """
        参数 （模型，页行数，页码，是否返回统计结果）
        返回 (查询结果， 总页数， 总行数)
    """
    page =  Paginator(model, size)
    return page.get_page(index), [page.num_pages if count else None][0], [page.count if count else None][0]

def result(code: int = 200, result: object='', msg: str = ''):
    return to_json({
        'code': code,
        'result': result,
        'msg': msg
    })
